﻿using Common.Core.Exceptions;
using Common.Core.Extension;
using Microsoft.AspNetCore.JsonPatch;
using NetByDocker.Domain.Model.HttpMange;
using NetByDocker.Model.HttpMange;

namespace NetByDocker.Controllers;

/// <summary>
/// 不操作数据库只是测试控制器
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class HttpSampleController : ControllerBase
{
    private static readonly List<UserDto> _userDtoList = Enumerable.Range(0, 100)
                                                                   .Select(t => new UserDto
                                                                                {
                                                                                    Name = "张三" + t,
                                                                                    Sex = "男",
                                                                                    UserId = 6974150586715897857 + t
                                                                                })
                                                                   .ToList();

    private readonly ILogger<HttpSampleController> _logger;

    public HttpSampleController(ILogger<HttpSampleController> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    /// <exception cref="ParameterException"></exception>
    [HttpPost("user/page")]
    public UserPageResult GetList([FromBody] UserPageRequest request)
    {
        if (request is null)
            throw new ParameterException("参数不能为null");

        var total = _userDtoList.Count;

        var list = _userDtoList.WhereIF(request.Name.IsNotNullOrWhiteSpace(), t => t.Name.Contains(request.Name))
                               .Skip(request.PageSize * (request.PageIndex - 1))
                               .Take(request.PageSize)
                               .ToList();
        return new UserPageResult { Total = total, UserList = list };
    }

    /// <summary>
    /// 获取用户详情
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ParameterException"></exception>
    [HttpGet("user/details")]
    public UserDto? GetUserDetails(long userId)
    {
        if (_userDtoList.All(t => t.UserId != userId))
            throw new ParameterException("未找到用户标识");
        _logger.LogInformation(HttpContext.Request.Headers.Authorization.FirstOrDefault());
        return _userDtoList.Find(t => t.UserId == userId);
    }

    [HttpPost("user/add")]
    public bool Add([FromBody] UserDto request)
    {
        if (_userDtoList.Any(t => t.UserId == request.UserId))
            throw new ParameterException("用户标识已经存在");
        _logger.LogInformation(DateTime.Now + "   " + HttpContext.Request.Headers.Authorization.FirstOrDefault());
        _userDtoList.Add(request);
        return true;
    }

    [HttpPut("user/update")]
    public bool Update(UserDto userDto)
    {
        if (userDto is null)
            throw new ParameterException("参数不能为空");

        _logger.LogInformation(DateTime.Now + "    " + HttpContext.Request.Headers.Authorization.FirstOrDefault());
        var currUser = _userDtoList.Find(t => t.UserId == userDto.UserId);
        if (currUser is null)
            throw new ParameterException("用户标识不存在");

        currUser.Name = userDto.Name;
        currUser.Sex = userDto.Sex;
        return true;
    }

    [HttpPatch("user/update2/{userId}")]
    public UserDto Update2([FromRoute] long userId, JsonPatchDocument<UserDto> jsonPatch, [FromServices] IMapper mapper)
    {
        var entity = _userDtoList.Find(t => t.UserId == userId);
        if (entity is null)
            throw new ParameterException("用户标识无效");

        _logger.LogInformation(DateTime.Now + "    " + HttpContext.Request.Headers.Authorization.FirstOrDefault());
        var dto = mapper.Map<UserDto>(entity);
        jsonPatch.ApplyTo(dto, ModelState);

        var user = _userDtoList.Find(t => t.UserId == userId);
        mapper.Map(dto, user);
        return user;
    }

    [HttpDelete("user")]
    public bool Delete(long userId)
    {
        var entity = _userDtoList.Find(t => t.UserId == userId);
        if (entity is null)
            throw new ParameterException("用户标识不存在");

        _logger.LogInformation(DateTime.Now + "    " + HttpContext.Request.Headers.Authorization.FirstOrDefault());
        _userDtoList.Remove(entity);
        return true;
    }

    /// <summary>
    /// 上传用户头像
    /// </summary>
    /// <param name="img"></param>
    /// <param name="userId"></param>
    /// <returns></returns>
    /// <exception cref="ParameterException"></exception>
    [HttpPost("user/uploadImg")]
    public string Upload(IFormFile img, [FromForm] long userId)
    {
        if (img is null)
            throw new ParameterException("用户头像不能为null");

        _logger.LogInformation(DateTime.Now + "    " + HttpContext.Request.Headers.Authorization.FirstOrDefault());
        var entity = _userDtoList.Find(t => t.UserId == userId);
        if (entity is null)
            throw new ParameterException("用户标识不存在");

        return img.FileName;
    }

    /// <summary>
    /// 更新用户名称
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    /// <exception cref="ParameterException"></exception>
    [HttpPost("user/updatename")]
    public bool UpdateName([FromForm] long userId, [FromForm] string name)
    {
        var entity = _userDtoList.Find(t => t.UserId == userId);
        if (entity is null)
            throw new ParameterException("用户标识不存在");

        _logger.LogInformation(DateTime.Now + "    " + HttpContext.Request.Headers.Authorization.FirstOrDefault());

        entity.Name = name;

        return true;
    }
}